import 'package:flutter/material.dart';
import 'package:flutter_broadcasts/flutter_broadcasts.dart';
import 'package:get/get.dart';
import 'package:hc_bot_pro/chat/controller_bot.dart';
import 'package:hc_bot_pro/chat/state.dart';
import 'package:hc_bot_pro/common/model/chat/chat.dart';
import 'package:hc_bot_pro/common/routes.dart';

import 'controller.dart';

extension ControllerBroadcast on ChatController {
  void setUpBroadcastReceiver() {
    BroadcastReceiver receiver = BroadcastReceiver(
      names: <String>["com.hc.ai.bot.MESSAGE_RECEIVED"],
    );
    receiver.messages.listen((broadcast) async {
      debugPrint("ControllerBroadcast: $broadcast");
      final msg = broadcast.data?["message"] ?? "";
      if (!state.isSleeping ||
          msg.isEmpty ||
          Get.currentRoute != Routes.kChat) {
        return;
      }
      addChat(ChatModel.fromOther(msg));
      await say(phase: msg);
    });
    receiver.start();
  }
}
